package com.menusifu.cloudmenu.dao.impl;

import com.menusifu.cloudmenu.dao.SaleItemDao;
import com.menusifu.cloudmenu.entity.SaleItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author xie
 * @date 2019/1/9 16:52
 * @description:
 */
@Repository
public class SaleItemDaoImpl implements SaleItemDao {
    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public List<SaleItem> getAllSaleItems() {
        Query query = new Query(Criteria.where("deleted").is(Boolean.FALSE));
        return mongoTemplate.find(query, SaleItem.class);
    }

    @Override
    public void addSaleItem(SaleItem saleItem) {
        mongoTemplate.insert(saleItem, "SaleItem");
    }

    @Override
    public void updateSaleItem(SaleItem saleItem) {
        Query query = new Query(Criteria.where("id").is(saleItem.getId()).and("deleted").is(Boolean.FALSE));
        Update update = Update.update("itemName", saleItem.getItemName())
                .set("description", saleItem.getDescription())
                .set("lastUpdatedBy", saleItem.getLastUpdatedBy())
                .set("thumbPath", saleItem.getThumbPath())
                .set("price", saleItem.getPrice())
                .set("lastUpdated", saleItem.getLastUpdated())
                .set("printerNames", saleItem.getPrinterNames());
        mongoTemplate.findAndModify(query, update, SaleItem.class);
    }

    @Override
    public void deleteSaleItemById(String id) {
        Query query = new Query(Criteria.where("id").is(id).and("deleted").is(Boolean.FALSE));
        Update update = Update.update("deleted", Boolean.TRUE);
        mongoTemplate.findAndModify(query, update, SaleItem.class);
    }

    @Override
    public SaleItem getSaleItemById(String id) {
        Query query = new Query(Criteria.where("id").is(id).and("deleted").is(Boolean.FALSE));
        return mongoTemplate.findOne(query, SaleItem.class);
    }

    @Override
    public List<SaleItem> batchAddSaleItems(List<SaleItem> saleItems) {
        return (List<SaleItem>) mongoTemplate.insert(saleItems, SaleItem.class);
    }

    @Override
    public List<SaleItem> getSaleItemsByCategoryId(String categoryId) {
        Query query = new Query(Criteria.where("categoryId").is(categoryId).and("deleted").is(Boolean.FALSE));
        return mongoTemplate.find(query, SaleItem.class);
    }

    @Override
    public void deleteSaleItemByCatId(String categoryId) {
        Query query = new Query(Criteria.where("categoryId").is(categoryId).and("deleted").is(Boolean.FALSE));
        Update update = Update.update("deleted", Boolean.TRUE);
        mongoTemplate.findAndModify(query, update, SaleItem.class);
    }
}
